<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">

    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（除ID外所有字段可查）"
                style="width: 21%"
                clearable></el-input>
      <!--      <el-button @click="Load" type="primary" style="margin-left: 10px">查询</el-button>-->
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
    >
      <!--      <el-table-column sortable fixed prop="userId" width="80" label="用户ID"/>-->
      <!--      <el-table-column sortable fixed prop="roleId" width="80"  label="角色ID"/>-->
      <el-table-column sortable prop="username" width="280" label="用户名"/>
      <!--      <el-table-column sortable prop="nickname" width="180"  label="昵称"/>-->
      <el-table-column sortable prop="roleName" width="180" label="角色"/>
      <el-table-column sortable prop="description" min-width="230" label="描述"/>

      <el-table-column sortable prop="isDeleted" width="180" label="状态">
        <template #default="scope">
          <span :style="scope.row.isDeleted ? { color: 'red', 'font-weight': 'bold' } :
                        scope.row.isDeleted === '' ? { color: 'gray' } : {}">
            {{
              scope.row.isDeleted ? '角色已禁用' :
                  (scope.row.isDeleted === false ? '角色活跃中' : '未分配')
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column sortable fixed="right" label="操作" min-width="90">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
          <!--@confirm="handleDelete(scope.row.id)"代表二次确认时删除-->
          <!--          <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.userId,scope.row.roleId)">-->
          <!--            <template #reference>-->
          <!--              <el-button type="text" :icon="Remove">取消分配</el-button>-->
          <!--            </template>-->
          <!--          </el-popconfirm>-->
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[10, 15, 20,30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>

    <div style="margin: 10px 0">
      <!--   layout，表示需要显示的内容 prev表示上一页，next为下一页 -->
      <!--   jumper表示跳页元素，total表示总条目数，size用于设置每页显示的页码数量-->

      <!--编辑弹框-->
      <div>
        <!--   centerDialogVisible是一个变量，需要在script中定义一下，默认为false     -->
        <el-dialog v-model="data.centerDialogVisible" title="请更新该用户的角色信息" width="30%" center>
          <el-form :model="data.form" label-width="60px" ref="userTableFormRef">

            <el-form-item style="margin-left: 50px" label="角 色">
              <el-select v-model="data.form.roleId" placeholder="请选择角色" style="width: 240px">
                <el-option
                    v-for="item in data.roles"
                    :key="item.roleId"
                    :label="item.roleName"
                    :value="item.roleId"
                >
                  <span style="float: left">{{ item.roleName }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px;"
                  >{{ item.description }}</span>
                </el-option>
              </el-select>
            </el-form-item>


            <el-form-item style="margin-left: 50px" label="描 述">
              <el-input v-model="data.form.description" style="width: 80%;" disabled/>
            </el-form-item>


            <el-form-item style="margin-left: 50px" label="状 态">
              <div class="mb-2 flex items-center text-sm">
                <el-radio-group v-model="data.form.isDeleted" class="ml-4" :disabled="isStatusDisabled">
                  <el-radio :label="false">活跃</el-radio>
                  <el-radio :label="true">禁用</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.centerDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="save">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>

    </div>
  </div>

  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import {computed, reactive, ref} from "vue";
import {Edit} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {useRouter} from "vue-router";
import {ElLoading, ElMessage} from 'element-plus';

const dataString = localStorage.getItem('data');
const userLoginData = dataString ? JSON.parse(dataString) : null;

const userTableFormRef = ref();


const data = reactive({
  //弹窗默认关闭
  centerDialogVisible: false,
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 10,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  //编辑表单
  form: {
    userId: "",
    roleId: "",
    username: "",
    nickname: "",
    roleName: "",
    description: "",
    isDeleted: ""
  },
  //角色表单
  roles: {
    roleId: "",
    roleName: "",
    description: "",
    createTime: "",
    isDeleted: ""
  },
  oldRoleId: ""
});

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  console.log("搜索框关键词：", data.SearchKeyWord);

  request.get(`/user/roles/userRoles?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        console.log("角色管理数据：", response);
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除
const handleDelete = async (userId, roleId) => {

  try {
    const res = await request.delete("/user/roles/delete/" + userId + "/" + roleId);
    console.log(res);
  } catch (e) {
    console.log(e);
  }

  handleCurrentChange(1);
};

//编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));//让form对象独立出来，还能包含那一行的数据
  request.get("/roles/list").then((response) => {
    data.roles = response.data;
    console.log("角色列表：", data.roles);
  })

  data.centerDialogVisible = true;
  data.oldRoleId = data.form.roleId != null ? data.form.roleId : -1;//保存旧的角色id;
};


//表单点击确认执行：关闭表单；向后端传数据
const save = async () => {
  data.centerDialogVisible = false;

  const editData = {
    userId: data.form.userId,
    roleId: data.form.roleId,//更新后的roleId
    isDeleted: data.form.isDeleted ? 1 : 0
  }

  // 使用await等待PUT请求完成
  try {
    const response = await request.put(`/user/roles/edit?oldRoleId=${data.oldRoleId}`, editData);
    if (response.code === 200) {
      ElMessage.info(response.data);
    } else {
      ElMessage.error(response.data);
    }
  } catch (error) {
    console.log("编辑失败：", error);
  }

  // 然后调用Load函数
  Load();

};


const router = useRouter();

const isStatusDisabled = computed(() => {
  return data.form.roleId === '' || data.form.roleId == null;
});

</script>
